package ua.tach.shortl.logic;

import ua.tach.shortl.Renderer;

import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;

public class Semaphore {
	// Possible types:
	// 0 - no semaphors
	// 1 - switch
	// 2 - light
	// 3 - tupik
	public int semType;
	public int semSignal;
	private int semIndex;
	private int dir;
	private float rot;
	Vector2 pos = new Vector2();

	public Semaphore () {
		semType = 0;
	}

	private void indexUpd() {
		switch (semType) {
		case 1: // switch, signals   right - 0,  left - 1,  forw - 2
			semIndex = semSignal + 2;
			break;
		case 2: // light , 0- green, 1 - red
			semIndex = semSignal;
			break;
		default:
			semIndex = 5; // tupik
		}
		rot = semph[semIndex].rotate+90*(4-dir);
		//System.out.println("Sem: t "+semIndex+" rot " + rot);
	}

	public Semaphore (Point p, int type, int d) {
		pos.set(p.x, p.y);
		semType = type;
		dir = d;
		indexUpd();
	}

	public void setType (int t) {
		semType = t;
		//System.out.println("Set semtype " + semType);
		indexUpd();
	}

	public void setSignal(int s, int dir) {
		//System.out.println("Set Dir: " + dir + " semtype " + semType);
		if (semType == 1)
			semSignal = dir;
		else semSignal = s;
		indexUpd();
	}

	public void render(GL10 gl, int state) {
		gl.glEnable(GL10.GL_BLEND);
		gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		semph[semIndex].tx().bind();
		gl.glPushMatrix();
		gl.glTranslatef( pos.x, 0, pos.y );
		gl.glRotatef(rot, 0, rot, 0);
		gl.glTranslatef( semph[semIndex].delta.x , 0, semph[semIndex].delta.y );
		//gl.glScalef(3, 3, 3);
		semph[semIndex].mesh().render(GL10.GL_TRIANGLES);
//		gl.glColor4f(1.f, 1.f, 1.f, 1.f);
//		gl.glDisable(GL10.GL_BLEND);
		gl.glPopMatrix();
	}

	private static class SemaphoreTypes {
		private static final int BASEINDEX = 13;
		private int index;
		public float rotate;
		public Vector2 delta;

		public SemaphoreTypes (int i, float r, Vector2 d) {
			index = i;
			delta = d;
			rotate = r;
		}

		public Mesh mesh () {
			return Renderer.toLoad[BASEINDEX+index].m;
		}

		public Texture tx () {
			return Renderer.toLoad[BASEINDEX+index].tx;
		}
	}

	private static SemaphoreTypes[] semph = {
		new SemaphoreTypes( 0, 180, new Vector2(0, 0)),
		new SemaphoreTypes( 1, 180, new Vector2(0, 0)),
		new SemaphoreTypes( 2, 0, new Vector2(0, 0)),
		new SemaphoreTypes( 3, 0, new Vector2(0, 0)),
		new SemaphoreTypes( 4, 0, new Vector2(0, 0)),
		new SemaphoreTypes( 5, 0, new Vector2(0, 0)),
	};


	public static class NullSem extends Semaphore implements Null {
		private NullSem() {
		}

		@Override
		public void render(GL10 gl) {
		}
		@Override
		public void render(GL10 gl, int s) {
		}
	}

	public static final NullSem NULL = new NullSem();
}
